import { GET_USERINFO, RECORD_USERINFO, OUT_LOGIN, SAVE_GEOHASH, RECORD_ADDRESS, RECORD_SHOPDETAIL, INIT_BUYCART, ADD_CART, REDUCE_CART, CLEAR_CART } from './mutation-types';
import { setStore, getStore } from '@/config/mUtils';
export default {
  //获取用户信息存入vuex
  [GET_USERINFO](state, info) {
    // console.log(state.userInfo);
    // console.log(info);
    if (state.userInfo && (state.userInfo.username !== info.username)) {
      return;
    }
    if (!state.login) {
      return
    }
    if (!info.message) {
      state.userInfo = { ...info };
    } else {
      state.userInfo = null;
    }
  },
  // 记录用户数据
  [RECORD_USERINFO](state, info) {
    state.userInfo = info;
    state.login = true;
    setStore('user_id', info.user_id);
  },
  // 退出登录，重置相关状态
  [OUT_LOGIN](state) {
    state.userInfo = null;
    state.login = false;
  },
  [SAVE_GEOHASH](state, geohash) {
    state.geohash = geohash
  },
  [RECORD_ADDRESS](state, { latitude, longitude }) {
    state.latitude = latitude;
    state.longitude = longitude
  },
  [RECORD_SHOPDETAIL](state, detail) {
    state.shopDetail = detail
  },
  [INIT_BUYCART](state) {
    let initCart = getStore('buyCart');
    if (initCart) {
      state.cartList = JSON.parse(initCart);
    }
  },
  [ADD_CART](state, {
    shopid,
    category_id,
    item_id,
    food_id,
    name,
    price,
    specs,
    packing_fee,
    sku_id,
    stock
  }) {
    let cart = state.cartList;
    let shop = cart[shopid] = (cart[shopid] || {});
    let category = shop[category_id] = (shop[category_id] || {});
    let item = category[item_id] = (category[item_id] || {});
    if (item[food_id]) {
      item[food_id]['num']++;
    } else {
      item[food_id] = {
        "num": 1,
        "id": food_id,
        "name": name,
        "price": price,
        "specs": specs,
        "packing_fee": packing_fee,
        "sku_id": sku_id,
        "stock": stock
      };
    }
    state.cartList = { ...cart };
    //存入localStorage
    setStore('buyCart', state.cartList);
  },
  [REDUCE_CART](state, {
    shopid,
    category_id,
    item_id,
    food_id
  }) {
    let cart = state.cartList;
    let shop = (cart[shopid] || {});
    let category = (shop[category_id] || {});
    let item = (category[item_id] || {});
    if (item && item[food_id]) {
      if (item[food_id]['num'] > 0) {
        item[food_id]['num']--;
        state.cartList = { ...cart };
        //存入localStorage
        setStore('buyCart', state.cartList);
      } else {
        //商品数量为0，则清空当前商品的信息
        item[food_id] = null;
      }
    }
  },
  [CLEAR_CART](state, shopid) {
    state.cartList[shopid] = null;
    state.cartList = { ...state.cartList };
    setStore('buyCart', state.cartList);
  }

}